package dao;

import entity.User;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DBUtil;

import java.sql.SQLException;
import java.util.List;

public class UserDao {
    QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());

    //可以将下划线命名的改为驼峰命名
    BeanListHandler<User> blh = new BeanListHandler<>(
            User.class, new BasicRowProcessor(new GenerousBeanProcessor()));

    /**
     * 添加用户
     * @return 插入数据影响的行数
     */
    public int add(User user){
        String sql = "insert into user values(?,?,?,?,?,?)";
        try {
            return queryRunner.update(sql, user.getIdNumber(), user.getUserName(), user.getPassword(),
                    user.getPhone(), user.getRealName(), user.getBelongPlace());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询用户
     */
    public List<User> query(String sql, Object... params){
        try {
            return queryRunner.query(sql, blh, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除用户
     */
    public int delete(String username){
        String sql = "delete from user where user_name=?";
        try {
            return queryRunner.update(sql, username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取所有用户的数据
     */
    public List<User> getAll(){
        String sql = "select * from user";
        try {
            return queryRunner.query(sql, blh);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}